"""
====================================================================
Filename :    merge_pdf_files.py
Description : Merge multiple pdf files，批量合并文件夹下pdf文件
Solution:
          1 use os.walk get names of pdf files.
          2 use PyPDF2 to merge pdf files
Copyright :  2023 ZAOYANG
Revision :   $Revision:1.0
====================================================================
"""
from PyPDF2 import PdfFileReader, PdfFileWriter, PdfWriter, PdfReader
import os


class merge_pdf:
    """
    Merge multiple pdf files
    """

    def __init__(self, pdf_files_dir: str, output_dir: str):
        '''
        description: inition
        :param pdf_files_dir: path of pdf files or full path of pdf file
        :param output_dir: full path of output's result
        '''
        self.pdf_files_dir = pdf_files_dir
        self.output_dir = output_dir
        self.fileName_list = []

    def get_fileName_list(self):
        """
        description: get names of pdf files
        :return: none
        """
        for root, dirs, files in os.walk(self.pdf_files_dir):
            for name in files:
                if '.pdf' in name:
                    self.fileName_list.append((os.path.join(root, name)))

    def mergePdf(self):
        """
        description:merge pdf files
        :return: none
        """
        pdfFileWrite = PdfWriter()
        for file in self.fileName_list:
            pdfReader = PdfReader(open(file, 'rb'))
            numPages = len(pdfReader.pages)
            for index in range(0, numPages):
                pageObj = pdfReader.pages[index]
                pdfFileWrite.add_page(pageObj)
            pdfFileWrite.write(open(self.output_dir, 'wb'))


if __name__ == '__main__':
    # 这里需要填写要合并的pdf所在目录，注意最后一个\需要转义，所以有两个\\
    pdf_file_dir = r"D:\Downloads\qqdownloads\04\\"
    # 这里输入最后合并出来的pdf的全局路径
    output_dir = r"D:\Downloads\qqdownloads\04\模拟.pdf"
    mergePdf = merge_pdf(pdf_file_dir, output_dir)
    mergePdf.get_fileName_list()
    mergePdf.mergePdf()
